package cnki.tpi.kbatis.config;

import cn.hutool.core.util.StrUtil;
import cnki.tpi.kbatis.nodehandler.NodeHandler;
import cnki.tpi.kbatis.sqlsource.iface.SqlSource;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName XMLStatementBuilder
 * @Description 解析文件中 CRUD 等标签
 * @Author 小黄
 * @Date 2019/11/12 20:36
 * @Version 1.0
 */
public class XMLStatementBuilder {
    private Configuration configuration;
    private Map<String, NodeHandler> map = new HashMap<String, NodeHandler>();

    public XMLStatementBuilder(Configuration configuration) {
        this.configuration = configuration;
    }


    /**
     * 解析 Select Statement 标签
     *
     * @param selectElement
     * @param namespace
     */
    public void parseStatement(Element selectElement, String namespace) {
        String id = selectElement.attributeValue("id");
        if (id == null || id.equals("")) {
            return;
        }
        String statementId = namespace + "." + id;
        String parameterType = selectElement.attributeValue("parameterType");
        Class<?> parameterClass = resolveType(parameterType);
        String resultType = selectElement.attributeValue("resultType");
        Class<?> resultClass = resolveType(resultType);
        String statementType = selectElement.attributeValue("statementType");
        statementType = statementType == "" || selectElement == null ? "prepared" : statementType;
        // 解析SQL信息
        SqlSource sqlSource = createSqlSource(selectElement);
        MappedStatement mappedStatement = new MappedStatement(statementId, parameterClass, resultClass, statementType, sqlSource);
        configuration.addMappedStatement(statementId, mappedStatement);
    }

    /**
     * 解析 SQl 信息
     *
     * @param selectElement
     * @return
     */
    private SqlSource createSqlSource(Element selectElement) {
        XMLScriptParser xmlScriptParser = new XMLScriptParser();
        SqlSource sqlSource = xmlScriptParser.parseScriptNode(selectElement);
        return sqlSource;
    }


    /**
     * 获取类型信息
     *
     * @param parameterType
     * @return
     */
    private Class<?> resolveType(String parameterType) {
        if (StrUtil.isEmpty(parameterType)) {
            return null;
        }
        try {
            Class<?> clazz = Class.forName(parameterType);
            return clazz;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
